package com.mysql.test;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author sunpeng
 * @Date 2021-07-06 17:03
 */
public class Transaction {

    @Test
    public void test1() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=utf-8";
        Connection connection = DriverManager.getConnection(url, "root", "610527");

        connection.setAutoCommit(false);
        String sql="update account set money =money- ? where id = ?";
        PreparedStatement ps = connection.prepareStatement(sql);

        try {
            //转入
            ps.setDouble(1, 100);
            ps.setLong(2,1);
            ps.executeUpdate();
            //异常
            int a = 1/0;
            //转出
            ps.setDouble(1, -100);
            ps.setLong(2,2);
            ps.executeUpdate();
        }catch (Exception e){
            connection.rollback(); //回滚
        }finally {
            connection.commit();  //提交
        }
        connection.close();
    }
    /*
     回滚connection.rollback();可以不用显式的写出，异常时不会提交。
     但是如果异常后try...catch掉异常，并且不显式地回滚，然后再显式地提交connection.commit();，会错误
     */
}
